package com.self.cloudmall.sso.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.self.cloudmall.common.constant.SsoConstant;
import com.self.cloudmall.common.dto.SocialLoginDto;
import com.self.cloudmall.common.utils.HttpUtil;
import com.self.cloudmall.common.utils.R;
import com.self.cloudmall.sso.client.MemberClient;
import com.self.cloudmall.sso.config.SmsConfig;
import com.self.cloudmall.sso.config.WeiboLoginConfig;
import com.self.cloudmall.sso.service.LoginService;
import com.self.cloudmall.sso.util.SmsUtil;
import com.self.cloudmall.sso.vo.LoginUserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class LoginServiceImpl implements LoginService {


    @Autowired
    private SmsConfig smsConfig;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MemberClient memberClient;

    @Autowired
    private WeiboLoginConfig weiboLoginConfig;

    @Override
    public R sendCode(String phone) {
        //防止盗刷

        //间隔120m重发验证
        String value = (String) redisTemplate.opsForValue().get(SsoConstant.REDIS_VALID_CODE_KEY + phone);
        if (!StringUtils.isEmpty(value)){
            String[] split = value.split("_");
            Long time = Long.parseLong(split[1]);
            if (time != null && (System.currentTimeMillis() - time) < SsoConstant.VALID_CODE_RESEND){
                return R.error("重发验证频繁，请稍等再试");
            }
        }

        String temp = "{\"code\":\"%s\"}";
        String code = SmsUtil.valideCode(5);
        log.info("手机号码：{},生成的验证码：{}",phone,code);
        redisTemplate.opsForValue().set(SsoConstant.REDIS_VALID_CODE_KEY+phone,code+"_"+System.currentTimeMillis(),
                SsoConstant.REDIS_VALID_EXPIRE, TimeUnit.MINUTES);

        return SmsUtil.sendCode(smsConfig.getAccessKey(), smsConfig.getAccessSecret(),
                smsConfig.getSignName(), smsConfig.getTemplateCode(), phone,String.format(temp,code));
    }

    @Override
    public R login(LoginUserVo loginUserVo) {
        return memberClient.login(loginUserVo);
    }

    @Override
    public R socialLogin(String code) {
        //SocialLoginDto
        //获取token
        Map<String,Object> params = Maps.newHashMap();
        params.put("client_id",weiboLoginConfig.getAppKey());
        params.put("client_secret",weiboLoginConfig.getAppSecret());
        params.put("grant_type","authorization_code");
        params.put("code",code);
        params.put("redirect_uri","http://sso.cloudmall.com/sso/success");
        JSONObject jsonObject = HttpUtil.doPost(weiboLoginConfig.getAccessUrl(),params);
        if (jsonObject == null){
            return R.error("获取三方授权token异常");
        }
        SocialLoginDto loginDto = jsonObject.toJavaObject(SocialLoginDto.class);
        if (loginDto == null || StringUtils.isEmpty(loginDto.getUid())
        || StringUtils.isEmpty(loginDto.getAccessToken())){
            return R.error("获取三方授权token异常");
        }
        loginDto.setUserInfoUrl(weiboLoginConfig.getUserInfoUrl());
        return memberClient.socialLogin(loginDto);
    }
}
